// 引入 lodash 库，用于数据处理和操作
const _ = require('lodash')
// 精确计算
const NP = require('number-precision')
// 引入 path 模块，用于处理文件和目录路径
const path = require('path')
// 获取项目根目录
const ROOT_DIR = path.join(__dirname, '../..')
// helpers 目录
const HELPERS_DIR = path.join(ROOT_DIR, 'helpers')
// 读取所有数据
const { readAllValues } = require(path.join(HELPERS_DIR, 'readAllValues.js'))

const allNumbers = Array.from({ length: 49 }, (_, i) => i + 1).map((num) => (num < 10 ? `0${num}` : `${num}`))
const comparator = (a, b) => _.toNumber(a) === _.toNumber(b)

const { calcAccuracySummary } = require(path.join(HELPERS_DIR, 'calcAccuracySummary.js'))

exports.calcHot = (region, topValue = 32) => {
  const allValues = readAllValues(region)
  const leadingElements = allValues.slice(0, topValue)
  const trailingElements = allValues.slice(topValue)

  // 统计次数
  const numberCounts = _.countBy(leadingElements, 'number')

  // 获取热门号码
  const getHotNumbers = (numberCounts, take = topValue) => {
    return (
      _.chain(numberCounts)
        // .countBy('number')
        .toPairs()
        .orderBy([1], ['desc'])
        .take(take)
        .map(([number]) => number)
        .value()
    )
  }

  // 前百个号码中出现次数最多的前24个号码
  const sortedNumberCounts = getHotNumbers(numberCounts, topValue)

  // 剩余数据
  const trailingList = trailingElements.map((item, index) => {
    let topNumbers
    if (index === 0) {
      topNumbers = sortedNumberCounts
    } else {
      if (numberCounts[item.number]) {
        numberCounts[item.number] += 1
      } else {
        numberCounts[item.number] = 1
      }
      topNumbers = getHotNumbers(numberCounts, topValue)
    }
    return {
      ...item,
      luckyNumbers: topNumbers,
      killNumbers: _.differenceWith(allNumbers, topNumbers, comparator),
      accuracy: topNumbers.map(Number).includes(Number(item.number)) ? 1 : 0
    }
  })

  // 剩余数据准确率
  const trailingAccuracyList = trailingList.map((item) => item.accuracy)

  // 前段数据/不参与计算准确率
  const leadingAccuracyList = leadingElements.map(() => 1)
  // 前段数据
  const leadingList = leadingElements.map((item) => {
    return {
      ...item,
      accuracy: 1
    }
  })
  // 统计数据
  const accuracySummary = calcAccuracySummary(trailingAccuracyList)

  return {
    // 前段数据/不参与计算准确率
    leadingAccuracyList,
    // 剩余数据准确率
    trailingAccuracyList,
    // 前段数据
    leadingList,
    // 剩余数据
    trailingList,
    // 统计次数
    numberCounts,
    // 统计数据
    accuracySummary
  }
}
